package com.example.smartcampus;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class Register extends AppCompatActivity {
    EditText register_password, name, account_number;
    Button date, submit;
    TextView setDate;
    RadioButton male, female;

    SQLiteDatabase dbRead;
    String name1, register_password1, setDate1, account1, male1, female1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_layout);
        getView();
        getBirthday();
        submit();
    }

    private void submit() {
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userName = account_number.getText().toString().trim();
                Log.d("user", "onClick: " + userName);
                if (illegalRegister(userName)) {
                    AlertDialog.Builder dialog1 = new AlertDialog.Builder(Register.this);
                    dialog1.setTitle("提示");
                    dialog1.setMessage("该用户名已存在，请重新输入。")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    account_number.setText("");
                                    dialog.cancel();
                                }
                            })
                            .show();
                } else {
                    // 创建“是否确认提交”的对话框
                    AlertDialog.Builder MyDialog = new AlertDialog.Builder(Register.this);
                    MyDialog.setTitle("提示");
                    MyDialog.setMessage("是否确认提交？");

                    MyDialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            // 获得前端的文本...
                            getDataText();
                            // 数据库操作...
                            setDataBase();

                            Intent intent = new Intent(Register.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    });
                    MyDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    }).show();
                }

            }
        });
    }

    public void getDataText() {
        //      获得前端的文本
        name1 = name.getText().toString().trim();
        register_password1 = register_password.getText().toString().trim();
        setDate1 = setDate.getText().toString().substring(5).trim();
        account1 = account_number.getText().toString().trim();
        male1 = "";
        female1 = "";
        if (male.isChecked()) {
            male1 = male.getText().toString().trim();
        } else {
            female1 = female.getText().toString().trim();
        }
    }

    public void setDataBase() {
//                                开起数据库并且存入
        Mydata dbOpenHelper = new Mydata(getApplicationContext(), "inform_database.db", null, 1);
        SQLiteDatabase dbWrite = dbOpenHelper.getReadableDatabase();
        String insertSql = "insert into information(name,sex,birthday,user,password) values(?,?,?,?,?)";
        SQLiteStatement sqLiteStatement = dbWrite.compileStatement(insertSql);
        sqLiteStatement.bindString(1, name1);
        if (male.isChecked()) {
            sqLiteStatement.bindString(2, male1);
        } else {
            sqLiteStatement.bindString(2, female1);
        }
        sqLiteStatement.bindString(3, setDate1);
        sqLiteStatement.bindString(4, account1);
        sqLiteStatement.bindString(5, register_password1);
        sqLiteStatement.executeInsert();
        dbOpenHelper.close();
        Intent intent = new Intent(Register.this, MainActivity.class);
        startActivity(intent);
        finish();

    }

    private boolean illegalRegister(String userName) {
        boolean isDuplicate = false;
        String[] projection = new String[]{"user"};
        String selection = "user = ?";
        String[] selectionArgs = new String[]{userName};
        // 获取数据库帮助器实例

        try {
            Mydata dbOpenHelper = new Mydata(getApplicationContext(), "inform_database.db", null, 1);
            dbRead = dbOpenHelper.getReadableDatabase();
        } catch (Exception e) {
            Log.d("database", "loadDatabase: 数据库加载失败");
        }
        try (Cursor cursor = dbRead.query("information", projection, selection, selectionArgs, null, null, null)) {
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") String dbUserName = cursor.getString(cursor.getColumnIndex("user"));
                if (dbUserName.equals(userName)) {
                    isDuplicate = true;
                }
            }
        } catch (Exception e) {
            // 处理可能的异常，例如数据库不可用等
            e.printStackTrace();
        }

        return isDuplicate;
    }

    private void getView() {
        register_password = findViewById(R.id.register_password);
        date = findViewById(R.id.date);
        submit = findViewById(R.id.submit);
        male = findViewById(R.id.male);
        female = findViewById(R.id.female);
        setDate = findViewById(R.id.setDate);
        name = findViewById(R.id.name);
        account_number = findViewById(R.id.account_number);
    }

    @SuppressLint("SetTextI18n")
    private void getBirthday() {

        // 设置初始的出生日期文本
        setDate.setText("出生日期：2023-12-28");

        date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(Register.this,
                        new DatePickerDialog.OnDateSetListener() {
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                setDate.setText("出生日期：" + year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                            }
                        }, 2023, 12, 28);
                datePickerDialog.show();
            }
        });
    }
}
